package com.xiejun;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class SocketProcessor implements Runnable {
    private Socket socket;
    public SocketProcessor(Socket socket) {
        this.socket = socket;
    }
    public void run() {
        processSocket();
    }
    private void processSocket() {
        //处理socket连接 读数据和写数据
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            inputStream.read(bytes);
            // 解析字节流，遇到⼀个空格就退出
            int pos = 0;
            int begin = 0, end = 0;
            for (; pos < bytes.length; pos++, end++) {
                if (bytes[pos] == ' ') break;
            }
            // 组合空格之前的字节流，转换成字符串就是请求⽅法
            StringBuilder method = new StringBuilder();
            for (; begin < end; begin++) {
                method.append((char) bytes[begin]);
            }
            System.out.println("method: " + method.toString());
            // 解析URL
            pos++;
            begin++;
            end++;
            for (; pos < bytes.length; pos++, end++) {
                if (bytes[pos] == ' ') break;
            }
            StringBuilder url = new StringBuilder();
            for (; begin < end; begin++) {
                url.append((char) bytes[begin]);
            }
            System.out.println("url: " + url.toString());
            // 解析协议版本
            pos++;
            begin++;
            end++;
            for (; pos < bytes.length; pos++, end++) {
                if (bytes[pos] == '\r') break;
            }
            StringBuilder protocol = new StringBuilder();
            for (; begin < end; begin++) {
                protocol.append((char) bytes[begin]);
            }
            System.out.println("protocol: " + protocol.toString());

            Request request = new Request(method.toString(), url.toString(), protocol.toString(), socket);
            Response response = new Response(request);
            
            // 使用ServletContainer动态查找和实例化Servlet
            HttpServlet servlet = ServletContainer.getInstance().getServlet(url.toString());
            if (servlet != null) {
                servlet.service(request, response);
            } else {
                // 如果没有找到匹配的Servlet，返回404错误
                response.setStatus(404, "Not Found");
                response.getOutputStream().write("No servlet found for URL: ".getBytes());
                response.getOutputStream().write(url.toString().getBytes());
            }
            
            //发送响应数据
            response.complete();
        } catch (IOException | ServletException e) {
            throw new RuntimeException(e);
        }
    }
}